package messengerserver.DBExch;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import messengercommon.dto.Message;

/**
 *
 * @author Samus
 */
public class PText {

    final String nombrearchivo = "log.txt";
    private static PText instance = new PText();
    String separator = System.getProperty("line.separator");

    public static PText getInstance() {
        return instance;
    }

    private PText() {
    }

    public void persistirMensaje(Message mess) {
        java.util.Date utilDate = new java.util.Date();
        try {
            Writer Candidateoutput = null;
            ArrayList<String> arr = leerLog();
            File Candidatefile = new File(nombrearchivo);

            Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
            String res = mess.getOrigen() + " a " + mess.getDestino() + " a las " + utilDate.toString() + " - " + mess.getMensaje();
            arr.add(res);
            for (String s : arr) {
                Candidateoutput.write(s + separator);
            }
            Candidateoutput.close();
        } catch (IOException ex) {
            Logger.getLogger(PText.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList<String> leerLog() throws IOException {
        ArrayList<String> text = new ArrayList<String>();
        try {
            FileReader fr = new FileReader(nombrearchivo);
            BufferedReader entrada = new BufferedReader(fr);
            String s;
            while ((s = entrada.readLine()) != null) {
                text.add(s);
            }
        } catch (java.io.FileNotFoundException fnfex) {
            System.out.println("se presento el error: " + fnfex.toString());
        }
        return text;
    }
}
